<template>
  <div class="checkout-container">
    <el-steps :active="activeStep" finish-status="success" class="checkout-steps">
      <el-step title="确认订单信息" />
      <el-step title="选择支付方式" />
      <el-step title="完成支付" />
    </el-steps>

    <!-- 步骤1：确认订单信息 -->
    <div v-if="activeStep === 0">
      <!-- 收货地址 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>收货地址</h2>
            <el-button type="primary" link @click="goToAddressManage">
              管理收货地址
            </el-button>
          </div>
        </template>

        <div v-if="addresses.length > 0" class="address-list">
          <el-radio-group v-model="selectedAddressId">
            <el-card v-for="address in addresses" :key="address.id" class="address-item"
              :class="{ 'address-selected': selectedAddressId === address.id }" @click="selectedAddressId = address.id">
              <div class="address-content">
                <div class="address-info">
                  <div class="address-header">
                    <span class="address-name">{{ address.name }}</span>
                    <span class="address-phone">{{ address.phone }}</span>
                    <el-tag v-if="address.isDefault === 1" type="success" size="small">默认地址</el-tag>
                  </div>
                  <div class="address-detail">
                    {{ formatAddress(address) }}
                  </div>
                </div>
                <el-radio :label="address.id" class="address-radio"></el-radio>
              </div>
            </el-card>
          </el-radio-group>
        </div>

        <el-empty v-else description="暂无收货地址">
          <el-button type="primary" @click="goToAddressManage">添加地址</el-button>
        </el-empty>
      </el-card>

      <!-- 商品清单 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>商品清单</h2>
          </div>
        </template>

        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="product-info">
                <el-image :src="row.mainImage" class="product-image" fit="cover" />
                <div class="product-details">
                  <div class="product-name">{{ row.name }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              <div class="price">¥{{ row.price }}</div>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="120">
            <template #default="{ row }">
              <div>{{ row.quantity }}</div>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <div class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 配送方式 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>配送方式</h2>
          </div>
        </template>

        <el-radio-group v-model="deliveryMethod">
          <el-radio label="express">快递配送</el-radio>
          <el-radio label="pickup">门店自提</el-radio>
        </el-radio-group>

        <div v-if="deliveryMethod === 'express'" class="delivery-options">
          <div class="delivery-time">
            <span class="option-label">送达时间：</span>
            <el-radio-group v-model="deliveryTime">
              <el-radio label="anytime">工作日/周末均可收货</el-radio>
              <el-radio label="workday">仅工作日收货</el-radio>
              <el-radio label="weekend">仅周末收货</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div v-if="deliveryMethod === 'pickup'" class="pickup-options">
          <div class="pickup-store">
            <span class="option-label">自提门店：</span>
            <el-select v-model="pickupStore" placeholder="请选择自提门店">
              <el-option v-for="store in stores" :key="store.id" :label="store.name" :value="store.id" />
            </el-select>
          </div>
        </div>
      </el-card>

      <!-- 发票信息 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>发票信息</h2>
          </div>
        </template>

        <el-radio-group v-model="invoiceType">
          <el-radio label="none">不开发票</el-radio>
          <el-radio label="electronic">电子发票</el-radio>
          <el-radio label="paper">纸质发票</el-radio>
        </el-radio-group>

        <div v-if="invoiceType !== 'none'" class="invoice-form">
          <el-form :model="invoiceForm" label-width="80px" class="invoice-form-content">
            <el-form-item label="发票抬头">
              <el-radio-group v-model="invoiceForm.titleType">
                <el-radio label="personal">个人</el-radio>
                <el-radio label="company">单位</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="抬头名称" v-if="invoiceForm.titleType === 'company'">
              <el-input v-model="invoiceForm.title" placeholder="请输入单位名称" />
            </el-form-item>

            <el-form-item label="税号" v-if="invoiceForm.titleType === 'company'">
              <el-input v-model="invoiceForm.taxNumber" placeholder="请输入纳税人识别号" />
            </el-form-item>

            <el-form-item label="发票内容">
              <el-select v-model="invoiceForm.content" placeholder="请选择">
                <el-option label="商品明细" value="detail" />
                <el-option label="商品类别" value="category" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 订单备注 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>订单备注</h2>
          </div>
        </template>

        <el-input v-model="orderRemark" type="textarea" rows="3" placeholder="选填，请填写与订单相关的要求" maxlength="100"
          show-word-limit />
      </el-card>

      <!-- 订单金额 -->
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>订单金额</h2>
          </div>
        </template>

        <div class="order-amount">
          <div class="amount-item">
            <span>商品总价：</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span>¥{{ shippingFee.toFixed(2) }}</span>
          </div>
          <div class="amount-item discount" v-if="discount > 0">
            <span>优惠金额：</span>
            <span>-¥{{ discount.toFixed(2) }}</span>
          </div>
          <div class="amount-item total">
            <span>应付总额：</span>
            <span class="total-price">¥{{ payableAmount.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 底部操作栏 -->
      <div class="checkout-actions">
        <div class="checkout-summary">
          <span class="total-label">应付总额：</span>
          <span class="total-price">¥{{ payableAmount.toFixed(2) }}</span>
        </div>
        <div class="checkout-buttons">
          <el-button @click="goBack">返回购物车</el-button>
          <el-button type="primary" @click="nextStep" :disabled="!canProceed">提交订单</el-button>
        </div>
      </div>
    </div>

    <!-- 步骤2：选择支付方式 -->
    <div v-if="activeStep === 1">
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>选择支付方式</h2>
          </div>
        </template>

        <div class="payment-methods">
          <el-radio-group v-model="paymentMethod">
            <div class="payment-method-item" @click="paymentMethod = 'alipay'">
              <el-radio label="alipay">
                <div class="payment-logo">
                  <img
                    src="https://img.alicdn.com/imgextra/i4/O1CN01Qg1L2L1aEEYLCJYQK_!!6000000003294-0-tps-800-800.jpg"
                    alt="支付宝" />
                  <span>支付宝</span>
                </div>
              </el-radio>
            </div>
            <div class="payment-method-item" @click="paymentMethod = 'wechat'">
              <el-radio label="wechat">
                <div class="payment-logo">
                  <img
                    src="https://img.alicdn.com/imgextra/i3/O1CN01FQW2Oa1vfGEX3vOjI_!!6000000006205-0-tps-800-800.jpg"
                    alt="微信支付" />
                  <span>微信支付</span>
                </div>
              </el-radio>
            </div>
            <div class="payment-method-item" @click="paymentMethod = 'unionpay'">
              <el-radio label="unionpay">
                <div class="payment-logo">
                  <img
                    src="https://img.alicdn.com/imgextra/i1/O1CN01Bd6Lw11Ux0LWGOoXl_!!6000000002581-0-tps-800-800.jpg"
                    alt="银联支付" />
                  <span>银联支付</span>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>

        <div class="order-info">
          <h3>订单信息</h3>
          <div class="order-info-item">
            <span>订单编号：</span>
            <span>{{ orderNumber }}</span>
          </div>
          <div class="order-info-item">
            <span>收货地址：</span>
            <span>{{ selectedAddress ? formatAddress(selectedAddress) : '未选择地址' }}</span>
          </div>
          <div class="order-info-item">
            <span>商品数量：</span>
            <span>{{ totalQuantity }}件</span>
          </div>
          <div class="order-info-item">
            <span>应付金额：</span>
            <span class="total-price">¥{{ payableAmount.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 底部操作栏 -->
      <div class="checkout-actions">
        <div class="checkout-summary">
          <span class="total-label">应付总额：</span>
          <span class="total-price">¥{{ payableAmount.toFixed(2) }}</span>
        </div>
        <div class="checkout-buttons">
          <el-button @click="prevStep">返回修改订单</el-button>
          <el-button type="primary" @click="confirmPayment" :disabled="!paymentMethod">确认支付</el-button>
        </div>
      </div>
    </div>

    <!-- 步骤3：完成支付 -->
    <div v-if="activeStep === 2">
      <el-card class="checkout-card">
        <template #header>
          <div class="card-header">
            <h2>支付结果</h2>
          </div>
        </template>

        <div class="payment-result">
          <div class="result-icon">
            <el-icon size="60" color="#67C23A">
              <CircleCheckFilled />
            </el-icon>
          </div>
          <div class="result-message">
            <h3>支付成功</h3>
            <p>您的订单已支付成功，感谢您的购买！</p>
          </div>
          <div class="order-detail">
            <div class="order-detail-item">
              <span>订单编号：</span>
              <span>{{ orderNumber }}</span>
            </div>
            <div class="order-detail-item">
              <span>支付金额：</span>
              <span>¥{{ payableAmount.toFixed(2) }}</span>
            </div>
            <div class="order-detail-item">
              <span>支付方式：</span>
              <span>{{ paymentMethodName }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 底部操作栏 -->
      <div class="checkout-actions">
        <div class="checkout-buttons centered">
          <el-button @click="viewOrder">查看订单</el-button>
          <el-button type="primary" @click="continueShopping">继续购物</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCheckFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const activeStep = ref(0)

// 收货地址
const addresses = ref([])

// 购物车商品
const cartItems = ref([])

// 自提门店
const stores = [
  { id: 1, name: '北京中关村店' },
  { id: 2, name: '北京朝阳大悦城店' },
  { id: 3, name: '上海南京东路店' },
  { id: 4, name: '广州天河城店' }
]

// 表单数据
const selectedAddressId = ref(null)
const deliveryMethod = ref('express')
const deliveryTime = ref('anytime')
const pickupStore = ref('')
const invoiceType = ref('none')
const invoiceForm = ref({
  titleType: 'personal',
  title: '',
  taxNumber: '',
  content: 'detail'
})
const orderRemark = ref('')
const paymentMethod = ref('')

// 订单信息
const orderNumber = ref('')
const totalAmount = ref(0)
const shippingFee = ref(0)
const discount = ref(0)

// 支付方式列表
const paymentMethods = ref([])

// 获取支付方式列表
const fetchPaymentMethods = async () => {
  try {
    const res = await request.get('/payment/methods')
    if (res && res.code === 200 && res.data) {
      paymentMethods.value = res.data
    }
  } catch (error) {
    console.error('获取支付方式失败:', error)
  }
}

// 获取用户地址列表
const fetchAddresses = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const res = await request.get(`/addresses/user/${userInfo.id}`)
    if (res && res.code === 200 && res.data) {
      addresses.value = res.data

      // 设置默认地址
      const defaultAddress = addresses.value.find(addr => addr.isDefault === 1)
      if (defaultAddress) {
        selectedAddressId.value = defaultAddress.id
      } else if (addresses.value.length > 0) {
        selectedAddressId.value = addresses.value[0].id
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 计算属性
const selectedAddress = computed(() => {
  return addresses.value.find(addr => addr.id === selectedAddressId.value)
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
})

const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const payableAmount = computed(() => {
  return totalPrice.value + shippingFee.value - discount.value
})

const canProceed = computed(() => {
  return selectedAddressId.value > 0 && cartItems.value.length > 0
})

const paymentMethodName = computed(() => {
  switch (paymentMethod.value) {
    case 'alipay': return '支付宝'
    case 'wechat': return '微信支付'
    case 'unionpay': return '银联支付'
    default: return '未选择'
  }
})

// 格式化地址
const formatAddress = (address) => {
  if (address.region && Array.isArray(address.region)) {
    return `${address.region.join(' ')} ${address.detailAddress} ${address.postalCode || ''}`
  } else {
    return `${address.province} ${address.city} ${address.district} ${address.detailAddress} ${address.postalCode || ''}`
  }
}

// 加载购物车数据
const loadCartItems = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 从后端API获取购物车数据
    const res = await request.get(`/cart/user/${userInfo.id}`)
    if (res && res.code === 200 && res.data) {
      // 转换后端数据格式为前端期望的格式
      cartItems.value = res.data.map(item => ({
        id: item.productId,
        cartId: item.id,
        name: item.productName,
        price: item.price,
        mainImage: item.productImage,
        quantity: item.quantity
      }))
    } else {
      cartItems.value = []
    }

    // 检查购物车是否为空
    if (cartItems.value.length === 0) {
      ElMessage.warning('购物车为空，请先添加商品')
      router.push('/home/cart')
      return
    }

    // 计算运费
    if (totalPrice.value >= 99) {
      shippingFee.value = 0
    } else {
      shippingFee.value = 10
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    ElMessage.error('获取购物车数据失败')
    router.push('/home/cart')
  }
}

// 生成订单号
const generateOrderNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')

  return `${year}${month}${day}${hour}${minute}${second}${random}`
}

// 前往地址管理页面
const goToAddressManage = () => {
  router.push('/home/addresses')
}

// 返回购物车页面
const goBack = () => {
  router.push('/home/cart')
}

// 下一步
const nextStep = () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法提交订单')
    return
  }

  // 生成订单号
  orderNumber.value = generateOrderNumber()

  activeStep.value++
}

// 上一步
const prevStep = () => {
  activeStep.value--
}

// 确认支付
const confirmPayment = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  try {
    // 1. 创建订单
    const orderData = {
      userId: JSON.parse(localStorage.getItem('userInfo') || '{}').id,
      orderNo: orderNumber.value,
      totalAmount: payableAmount.value,
      addressId: selectedAddressId.value,
      remark: orderRemark.value,
      items: cartItems.value.map(item => ({
        productId: item.id,
        productName: item.name,
        price: item.price,
        quantity: item.quantity
      }))
    }

    const orderRes = await request.post('/orders', orderData)
    if (!orderRes || orderRes.code !== 200) {
      ElMessage.error('创建订单失败')
      return
    }

    const orderId = orderRes.data.id
    // 保存订单信息用于支付成功页面显示
    orderNumber.value = orderRes.data.orderNo
    totalAmount.value = orderRes.data.totalAmount

    // 2. 创建支付
    const selectedPaymentMethod = paymentMethods.value.find(pm => pm.code === paymentMethod.value)
    const paymentData = {
      orderId: orderId,
      paymentMethodId: selectedPaymentMethod.id
    }

    const paymentRes = await request.post('/payment/create', paymentData)
    if (!paymentRes || paymentRes.code !== 200) {
      ElMessage.error('创建支付失败')
      return
    }

    // 3. 执行支付
    const executeData = {
      paymentNo: paymentRes.data.paymentNo,
      paymentMethodCode: paymentMethod.value
    }

    const executeRes = await request.post('/payment/pay', executeData)
    if (!executeRes || executeRes.code !== 200) {
      ElMessage.error('支付失败')
      return
    }

    ElMessage.success('支付成功')

    // 清空购物车
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (userInfo.id) {
      // 如果已登录，调用后端API清空购物车
      try {
        await request.delete(`/cart/user/${userInfo.id}`)
      } catch (error) {
        console.error('清空购物车失败:', error)
      }
    } else {
      // 如果未登录，清空localStorage
      localStorage.setItem('cartItems', '[]')
    }

    // 进入支付成功页面
    activeStep.value++

  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  }
}

// 查看订单
const viewOrder = () => {
  router.push('/home/orders')
}

// 继续购物
const continueShopping = () => {
  router.push('/home/products')
}

onMounted(() => {
  fetchAddresses()
  loadCartItems()
  fetchPaymentMethods()
})
</script>

<style scoped>
.checkout-container {
  padding: 20px;
}

.checkout-steps {
  margin-bottom: 30px;
}

.checkout-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 地址样式 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  cursor: pointer;
}

.address-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-selected {
  border: 1px solid #409EFF;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.2);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-header {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.address-name {
  font-size: 16px;
  font-weight: 500;
}

.address-phone {
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.5;
}

.address-radio {
  margin-right: 0;
}

/* 商品信息样式 */
.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  border-radius: 4px;
}

.product-name {
  font-size: 14px;
}

.price,
.subtotal {
  font-size: 14px;
  color: #606266;
}

.subtotal {
  color: #F56C6C;
  font-weight: 500;
}

/* 配送方式样式 */
.delivery-options,
.pickup-options {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.option-label {
  display: inline-block;
  width: 80px;
  color: #606266;
}

/* 发票表单样式 */
.invoice-form {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.invoice-form-content {
  max-width: 500px;
}

/* 订单金额样式 */
.order-amount {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.amount-item {
  display: flex;
  gap: 20px;
}

.amount-item.discount {
  color: #F56C6C;
}

.amount-item.total {
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.total-price {
  color: #F56C6C;
  font-weight: bold;
}

/* 底部操作栏样式 */
.checkout-actions {
  position: sticky;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.checkout-summary {
  font-size: 16px;
}

.total-label {
  margin-right: 10px;
}

.checkout-buttons {
  display: flex;
  gap: 15px;
}

.checkout-buttons.centered {
  margin: 0 auto;
}

/* 支付方式样式 */
.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.payment-method-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method-item:hover {
  background-color: #f5f7fa;
}

.payment-logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.payment-logo img {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

/* 订单信息样式 */
.order-info {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.order-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.order-info-item {
  display: flex;
  margin-bottom: 10px;
}

.order-info-item span:first-child {
  width: 80px;
  color: #606266;
}

/* 支付结果样式 */
.payment-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
}

.result-icon {
  margin-bottom: 20px;
}

.result-message {
  text-align: center;
  margin-bottom: 30px;
}

.result-message h3 {
  font-size: 24px;
  color: #67C23A;
  margin-bottom: 10px;
}

.result-message p {
  color: #606266;
}

.order-detail {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.order-detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

/* 深色模式适配 */
html.dark .address-phone,
html.dark .address-detail,
html.dark .option-label,
html.dark .order-info-item span:first-child,
html.dark .result-message p {
  color: #e5eaf3;
}

html.dark .address-item,
html.dark .payment-method-item {
  border-color: #363637;
}

html.dark .address-selected {
  border-color: #409EFF;
}

html.dark .delivery-options,
html.dark .pickup-options,
html.dark .invoice-form {
  border-top-color: #363637;
}

html.dark .amount-item.total {
  border-top-color: #363637;
}

html.dark .checkout-actions {
  background-color: #1d1e1f;
  border-top-color: #363637;
}

html.dark .payment-method-item:hover {
  background-color: #141414;
}

html.dark .order-info,
html.dark .order-detail {
  background-color: #141414;
}
</style>